package com.xinhe.web.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.QGoods;
import com.xinhe.web.entity.QTeamGoods;
import com.xinhe.web.entity.TeamGoods;
import com.xinhe.web.reposity.TeamBuyOrderRepository;
import com.xinhe.web.reposity.TeamBuyRepository;
import com.xinhe.web.reposity.TeamGoodsRepository;
import com.xinhe.web.response.TeamGoodsView;
import com.xinhe.web.util.Snowflake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import java.math.BigDecimal;
import java.util.*;

@Service
public class TeamGoodsService {
    @Autowired
    private TeamGoodsRepository teamGoodsRepository;
    @Autowired
    private TeamBuyOrderRepository teamBuyOrderRepository;
    @Autowired
    private TeamBuyRepository teamBuyRepository;
    @Autowired
    private AttachService attachService;
    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;

    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }

    public QueryResults<TeamGoodsView> pageTeamGoods(Long goodsId,Integer memberAmount,String remark,
                                                     String keyword,int pageNum, int pageSize) {
        QTeamGoods qTeamGoods = QTeamGoods.teamGoods;
        QGoods qGoods = QGoods.goods;
        BooleanBuilder builder = new BooleanBuilder();
        //builder.and(qTeamBuy.removed.eq(0));
        if (!Objects.isNull(keyword)) {
            builder.and(qGoods.name.like(keyword));
        }
        if (!Objects.isNull(goodsId)) {
            builder.and(qTeamGoods.goodsId.eq(goodsId));
        }
        if (!Objects.isNull(memberAmount)) {
            builder.and(qTeamGoods.memberAmount.eq(memberAmount));
        }

        QueryResults<TeamGoodsView> teamGoodsViewQueryResults = queryFactory.select(
                Projections.bean(
                        TeamGoodsView.class,
                        qTeamGoods.id,
                        qTeamGoods.memberAmount,
                        qTeamGoods.goodsId,
                        qTeamGoods.iconPath,
                        qTeamGoods.money,
                        qTeamGoods.memberAmount,
                        qGoods.name.as("goodsName"),
                        qGoods.dis
                )
        ).from(qTeamGoods)
                .leftJoin(qGoods).on(qTeamGoods.goodsId.eq(qGoods.id))
                .where(builder).offset(pageNum * pageSize).limit(pageSize).fetchResults();
        //对分页结果进行处理
        List<TeamGoodsView> results = teamGoodsViewQueryResults.getResults();
        // 创建一个用于存储修改后元组对象的列表
        List<TeamGoodsView> modifiedResults = new ArrayList<>();
        for (TeamGoodsView teamGoodsView : results) {
            int sumAmount = teamBuyOrderRepository.querySumAmount(teamGoodsView.getId());
            teamGoodsView.setSumAmount(sumAmount);
            // 将修改后的元组对象添加到列表中
            modifiedResults.add(teamGoodsView);
        }
        // 创建一个新的QueryResults对象，包含修改后的分页记录
        QueryResults<TeamGoodsView> modifiedQueryResults = new QueryResults<>(
                modifiedResults,
                teamGoodsViewQueryResults.getTotal(),
                teamGoodsViewQueryResults.getOffset(),
                teamGoodsViewQueryResults.getLimit()
        );
        return modifiedQueryResults;
    }

    @Transactional
    public Result saveTeamGoods(Long id,Long goodsId, Integer memberAmount, String remark, String iconPath,
                                BigDecimal money, Set<Long> attachIds) {
        TeamGoods teamGoods = teamGoodsRepository.findById(goodsId).get();

        if (id != null) {
            teamGoods.setGoodsId(goodsId);
            teamGoods.setMemberAmount(memberAmount);
            teamGoods.setIconPath(iconPath);
            teamGoods.setMoney(money);
            //teamGoods.setRemark(model.getRemark());
            teamGoodsRepository.saveAndFlush(teamGoods);
        } else {
            if (teamGoods != null) {
                return Result.failed(5001,"商品已添加到拼团商品");
            }
            teamGoods = new TeamGoods();
            teamGoods.setId(Snowflake.generateId());
            teamGoods.setGoodsId(goodsId);
            teamGoods.setMemberAmount(memberAmount);
            teamGoods.setIconPath(iconPath);
            teamGoods.setMoney(money);
            //teamGoods.setRemark(model.getRemark());
            teamGoodsRepository.save(teamGoods);
        }
        attachService.updateAttachByBusinessIdAndAttachIds(teamGoods.getId(), attachIds);
        return Result.ok();
    }

    public Result<TeamGoodsView> detailTeamGoods(Long teamGoodsId) {
        QTeamGoods qTeamGoods = QTeamGoods.teamGoods;
        QGoods qGoods = QGoods.goods;
        BooleanBuilder builder = new BooleanBuilder();
        TeamGoodsView teamGoodsView = queryFactory.select(
                Projections.bean(
                        TeamGoodsView.class,
                        qTeamGoods.id,
                        qTeamGoods.memberAmount,
                        qTeamGoods.goodsId,
                        qTeamGoods.iconPath,
                        qTeamGoods.money,
                        qTeamGoods.memberAmount,
                        qGoods.name.as("goodsName"),
                        qGoods.dis
                )
        ).from(qTeamGoods)
                .leftJoin(qGoods).on(qTeamGoods.goodsId.eq(qGoods.id))
                .where(builder).fetchOne();
        //对结果进行处理
        int sumAmount = teamBuyOrderRepository.querySumAmount(teamGoodsView.getId());
        teamGoodsView.setSumAmount(sumAmount);
        return Result.ok(teamGoodsView);
    }

    //@ANoRepeatRequest
    @Transactional
    public Result deleteTeamGoods(Long teamGoodsId) {
        HashSet<String> statuses = new HashSet<>();
        statuses.add("UN_PAY");
        statuses.add("PAYED");
        Integer countByTeamOrder = this.teamBuyOrderRepository.countByTeamGoodsIdAndStatus(teamGoodsId,statuses);

        if (countByTeamOrder.intValue() > 0) {
            return Result.failed(5001,"还有正在拼团的订单，无法删除");
        }
        HashSet<String> status = new HashSet<>();
        statuses.add("TEAMING");
        Integer countByTeamBuy = this.teamBuyOrderRepository.countByTeamGoodsIdAndStatus(teamGoodsId,status);
        if (countByTeamBuy.intValue() > 0) {
            return Result.failed(5001,"还有正在拼团的订单，无法删除");
        }
        this.teamGoodsRepository.deleteById(teamGoodsId);
        return Result.ok();
    }


}
